﻿using System;
using System.Collections;
using System.Configuration;
using System.Data;
using System.Web;
using System.Web.Security;
using System.Web.UI;
using System.Web.UI.WebControls;
using Runda.CMS.Bll;
using Runda.CMS.Common.Entity;
using Runda.CMS.Common.Utility;
using System.Collections.Generic;
using Telerik.Web.UI;
using System.Text;

namespace Runda.CMS.Portal.SalesManage
{
    public partial class AccountRecord : BasePage
    {
        public string SortString
        {
            get
            {
                if (ViewState["SortString"] == null)
                {
                    ViewState["SortString"] = "customername";
                }

                return ViewState["SortString"].ToString();
            }
            set { ViewState["SortString"] = value; }
        }

        

        protected void Page_Load(object sender, EventArgs e)
        {
            if (!IsPostBack)
            {

                DataTable dt = new BudgetBll().Companylist(base.CurrentUserID.ToString());
                ddlCompany.DataSource = dt;
                ddlCompany.DataTextField = "Departmentname";
                ddlCompany.DataValueField = "Departmentname";
                ddlCompany.DataBind();


                if (Request.QueryString["billYear"] != null)
                {
                    ddlBudgetYear.SelectedValue = Request.QueryString["billYear"];
                }
                if (Request.QueryString["billMonth"] != null)
                {
                    ddlBudgetMonth.SelectedValue = Request.QueryString["billMonth"];
                }
                if (Request.QueryString["company"] != null)
                {
                    ddlCompany.SelectedValue = Request.QueryString["company"];
                }


                BindGrid(1);
                Calculate();

                LoadRadTree("");

            }
        }
        protected void btnSearch_Click(object sender, EventArgs e)
        {
            BindGrid(AspNetPager1.CurrentPageIndex);
            Calculate();
        }

        protected void btnRefershBillInfo_Click(object sender, EventArgs e)
        {
            
        }

        protected void btnSaveSubItems_Click(object sender, EventArgs e)
        {
            string categoryCode="";

            SystemBll bll = new SystemBll();

            if (Text1.Value != "")
            {
                Guid ID = new Guid(Text1.Value);
                CtrtInstrumentCategoryEntity instrmentEntity = bll.Get<CtrtInstrumentCategoryEntity>(ID);
                if (instrmentEntity != null)
                {
                    categoryCode = instrmentEntity.categoryCode;
                }
            }

            if (hidCustomerID.Value == "") 
            {
                ClientScript.RegisterStartupScript(this.GetType(), "保存提示！", "alert('请指定客户。');", true);
                return;
            }

            if (ddlCompany.SelectedValue == "")
            {
                ClientScript.RegisterStartupScript(this.GetType(), "保存提示！", "alert('请选择记账公司。');", true);
                return;
            }
            if (Text1.Value == "" || categoryCode.Length < 6)
            {
                ClientScript.RegisterStartupScript(this.GetType(), "保存提示！", "alert('请输入正确的存货大类代码。');", true);
                return;
            }

            if (txtiNatSum.Text =="")
            {
                ClientScript.RegisterStartupScript(this.GetType(), "保存提示！", "alert('请输入金额。');", true);
                return;
            }
            if (txtiNatSum.Text=="")
            {
                ClientScript.RegisterStartupScript(this.GetType(), "保存提示！", "alert('请输入价税合计。');", true);
                return;
            }

            BGSalesBillsEntity entity = new BGSalesBillsEntity();
            entity.billGUID = Guid.NewGuid();
            entity.SourceType = 3;
            entity.UFAccountNo="000";
            entity.cBVCode = "调整" + ddlBudgetYear.SelectedValue + ddlBudgetMonth.SelectedValue + "01";
            entity.BillUnit = ddlCompany.SelectedValue;
            entity.BudgetUnit = ddlCompany.SelectedValue;
            entity.dDate = Convert.ToDateTime(ddlBudgetYear.SelectedValue +"-" +ddlBudgetMonth.SelectedValue + "-01");
            entity.billYear = Convert.ToInt16(ddlBudgetYear.SelectedValue);
            entity.billMonth = Convert.ToInt16(ddlBudgetMonth.SelectedValue);
            entity.CreatedOn = System.DateTime.Now;
            entity.CreatedBy = base.CurrentUserID;
            entity.Sales = "财务调整";
            entity.SalesGroup = "财务调整";
            entity.iNatSum = Convert.ToDecimal(txtiNatSum.Text);
            entity.iNatMoney = Convert.ToDecimal(txtiNatMoney.Text);
            entity.cMemo = txtMemo.Text.Trim();
            entity.cCategoryCode = categoryCode;
            entity.cCusCode = bll.Get<CtrtCustomerEntity>(new Guid(hidCustomerID.Value)).CustomerCode;
            entity.Deleted = false;
            //entity.Sales = hidSales.Value;

            bll.Insert(entity);
            ClientScript.RegisterStartupScript(this.GetType(), "保存提示！", "alert('保存成功！');", true);

            BindGrid(1);
            Calculate();
            
        }

        private void LoadRadTree(string categoryCode)
        {
            string categoryGUID="";
            //List<CtrtInstrumentCategoryEntity> categoryEntitys = new CtrtInstrumentCategoryBll().GetAll<CtrtInstrumentCategoryEntity>(" and parentGUID is null", "Order By categoryCode"); 
            DataTable dt = null;
            CtrtInstrumentCategoryBll bll = new CtrtInstrumentCategoryBll();
            dt = bll.GetInstrumentCategory("");//  and SUBSTRING(categorycode,1,2) in('01', '02')


            RadTreeView RadTreeProdType = RadComboBox_ProdType.Items[0].FindControl("RadTreeView_ProdType") as RadTreeView;
            //HtmlInputHidden Hidden_ProdTypeID = Page.FindControl("Text1") as HtmlInputHidden;
            //HtmlInputText txtSelectType = Page.FindControl("txt_SelectType") as HtmlInputText;
            if (RadTreeProdType != null)
            {
                RadTreeProdType.DataFieldID = "categoryGUID";
                RadTreeProdType.DataTextField = "categoryName";
                RadTreeProdType.DataValueField = "categoryGUID";
                RadTreeProdType.DataFieldParentID = "parentGUID";
                RadTreeProdType.DataSource = dt;
                RadTreeProdType.DataBind();
            }
            if (categoryCode != "")
            {
                Text1.Value = categoryCode;
                List<CtrtInstrumentCategoryEntity> categoryEntitys = new CtrtInstrumentCategoryBll().GetAll<CtrtInstrumentCategoryEntity>(" and parentGUID is null", "Order By categoryCode");

                if (categoryEntitys != null && categoryEntitys.Count > 0)
                {
                    categoryGUID = categoryEntitys[0].categoryCode;
                }

                if (categoryGUID != "")
                {
                txt_SelectType.Value = RadTreeProdType.FindNodeByValue(categoryGUID).Text;

                RadComboBox_ProdType.SelectedItem.Value = RadTreeProdType.FindNodeByValue(categoryGUID).Text;
                RadComboBox_ProdType.SelectedItem.Text = RadTreeProdType.FindNodeByValue(categoryGUID).Text;
                RadComboBox_ProdType.Text = RadTreeProdType.FindNodeByValue(categoryGUID).Text;
                }
            }

        }
        protected void gridAccessoryList_ItemCommand(object source, Telerik.WebControls.GridCommandEventArgs e)
        {
            if (e.CommandName.ToLower() == "delete")
            {

                BudgetBll bll = new BudgetBll();

                bll.DeleteBGSalesBill(new Guid(e.Item.OwnerTableView.DataKeyValues[e.Item.ItemIndex]["billGUID"].ToString()));

            }
            BindGrid(AspNetPager1.CurrentPageIndex);
            Calculate();
        }

        protected void gridAccessoryList_ItemDataBound(object sender, Telerik.WebControls.GridItemEventArgs e)
        {
            if (e.Item.ItemType == Telerik.WebControls.GridItemType.Item || e.Item.ItemType == Telerik.WebControls.GridItemType.AlternatingItem)
            {
                LinkButton lnkbtnDelete = e.Item.FindControl("lnkbtnDelete") as LinkButton;
                if (lnkbtnDelete != null)
                {
                    //DataRowView dv = e.Item.DataItem as DataRowView;
                    //if (new BudgetBll().GetBudgetSubmitStatus(ddlBudgetYear.SelectedValue.ToString(), dv["ProductManager"].ToString()) > 0 || !base.CheckUserHasFuction(1, "Func10011"))
                    //{ lnkbtnDelete.Visible = false; }

                    //lnkEdit.NavigateUrl = "~/Budget/SalesbudgetDetail.aspx?AssistID=" + dv["AssistID"].ToString();
                    lnkbtnDelete.OnClientClick = "return OnDelConfirm();";
                }
            }
        }

        protected void AspNetPager1_PageChanged(object sender, EventArgs e)
        {
            BindGrid(AspNetPager1.CurrentPageIndex);
            Calculate();
        }

        protected void btnRefersh_Click(object sender, EventArgs e)
        {
            BindGrid(AspNetPager1.CurrentPageIndex);
            Calculate();
        } 

        private void BindGrid(int pageindex)
        {
            string sb = getWhereClause();

            int RecordCount = 0;
            DataTable dt = new BillBll().GetSalesBills(sb, SortString, AspNetPager1.PageSize, pageindex, out RecordCount);

            AspNetPager1.RecordCount = RecordCount;
            gridAccessoryList.DataSource = dt;
            gridAccessoryList.DataBind();
        }

        private void Calculate()
        {
            string sb = getWhereClause();

            BudgetBll bll = new BudgetBll();
            DataTable dt = bll.CalcbillAmount(sb);

            if (dt != null && dt.Rows.Count > 0)
            {
                lblTotal.Text = "合计：   金额：" + string.Format("{0:N}", dt.Rows[0]["iNatMoney"]) + "；价税合计：" + string.Format("{0:N}", dt.Rows[0]["iNatSum"]);


            }
            else
            {

                lblTotal.Text = "";
            }
        }

        protected void gridAccessoryList_SortCommand(object source, Telerik.WebControls.GridSortCommandEventArgs e)
        {
            string OrderBy = e.SortExpression + " " + (e.NewSortOrder == Telerik.WebControls.GridSortOrder.Ascending ? "asc" : "desc");
            SortString = OrderBy;
            BindGrid(1);
            Calculate();
            

        }

        private string getWhereClause()
        { 
            StringBuilder sb = new StringBuilder();

            sb.Append(" and SourceType = 3");
            if (ddlBudgetYear.SelectedValue != string.Empty)
            {
                sb.Append(" and datepart(year,a.[dDate])  = ").Append(ddlBudgetYear.SelectedValue).Append("");
            }

            if (ddlBudgetMonth.SelectedValue != string.Empty)
            {
                sb.Append(" and datepart(month,a.[dDate])  = ").Append(ddlBudgetMonth.SelectedValue).Append("");
            }

            if (this.txtCustomerName.Text.Trim() != "")
            {
                sb.Append(" and c.[CustomerName]  like '%").Append(txtCustomerName.Text.Trim()).Append("%'");
            }

            //int RecordCount = 0;
            //RecordCount = new BudgetBll().getDataright(base.CurrentUserID.ToString());

            //if (RecordCount == 0)
            //{ sb.Append(" and ([productmanager] ='").Append(base.CurrentUserEntity.UserName).Append("'").Append(" or [biller] ='").Append(base.CurrentUserID.ToString()).Append("')"); }
            //else
            //{ sb.Append(" and [productmanager] in(").Append("select username from vw_sysUser where DepartmentID in(select DepartmentID from Cms_Sys_UserDepartment_DataRight where userid ='").Append(base.CurrentUserID.ToString()).Append("'))"); }

            if (ddlCompany.SelectedValue != "")
            {
                sb.Append(" and BillUnit='").Append(ddlCompany.SelectedValue.ToString()).Append("'");
            }
            
            if (txtCustomerName.Text.Trim() != "")
            {
                sb.Append(" and customerID in(").Append("select customerid from cms_ctrt_customer where customername like '%").Append(txtCustomerName.Text.Trim()).Append("%')");
            }
            
            

            return sb.ToString();
        }

        protected void btnExportExcel_Click(object sender, EventArgs e)
        {
            string Whereclause = getWhereClause();

            BudgetBll bll = new BudgetBll();

            DataTable dt = bll.ExportSalesBudgets(Whereclause, " [客户] asc ");

            Export.Export2Excel(dt, "销售预算一览表", Page.Response);

        }

        protected void lnkbtnSubmit_Click(object sender, EventArgs e)
        {

            BudgetBll bll = new BudgetBll();
            bll.SubmmitBudget(ddlBudgetYear.SelectedValue.ToString(), base.CurrentUserEntity.UserName);
            

        }

        protected void lnkbtnCheck_Click(object sender, EventArgs e)
        {

            BudgetBll bll = new BudgetBll();
            //bll.CheckBudget(ddlBudgetYear.SelectedValue.ToString(), base.CurrentUserEntity.UserName);
        }
    }
}
